<?

class deploy_sources_task extends system_task
{
	public function execute(array $params = array())
	{
		exec('svn up ' . PHLIGHT_PATH, $o, $r);
		echo implode("\n", $o) . "\n";

		exec('svn up ' . PROJECT_PATH, $o, $r);
		echo implode("\n", $o) . "\n\n";

		exec(PROJECT_PATH . '/run compile_load', $o, $r);
		echo implode("\n", $o) . "\n\n";

		if ( config::all()->deploy['sources'] ) foreach ( config::all()->deploy['sources'] as $ip )
		{
			$this->out('Updating sources: ' . $ip . '...');

			$connection = ssh2_connect($ip, 22);
			ssh2_auth_password($connection, config::all()->deploy['user'], config::all()->deploy['password']);

			$this->remote_execute($connection, 'svn up ' . PHLIGHT_PATH);
			$this->remote_execute($connection, 'svn up ' . PROJECT_PATH);
			$this->remote_execute($connection, PROJECT_PATH . '/run compile_load');

			$this->out('OK, done');
		}
		
		if ( config::all()->deploy['static'] ) foreach ( config::all()->deploy['static'] as $ip )
		{
			$this->out('Updating static servers: ' . $ip . '...');

			$connection = ssh2_connect($ip, 22);
			ssh2_auth_password($connection, config::all()->deploy['user'], config::all()->deploy['password']);

			$this->remote_execute($connection, 'svn up ' . PROJECT_PATH);

			$this->out('OK, done');
		}
	}

	protected function remote_execute( $con, $cmd )
	{
		$stream = ssh2_exec($con, $cmd);

		stream_set_blocking( $stream, true );
		while ( !feof($stream) ) echo fread($stream, 8);
		fclose($stream);
	}
}